
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
let jwt = require('jsonwebtoken');
const userModel = require("../models/userinfo")
const userinfo = userModel(sequelize);
var md5 = require('md5-node');

// 生成加盐
function randomCoding(n = 8) {
    //创建26个字母数组
    var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var idvalue = '';
    for (var i = 0; i < n; i++) {
        idvalue += arr[Math.floor(Math.random() * 26)];
    }
    return idvalue;
}

/**
 * 注册
 * */
router.post('/register', async (ctx) => {
    try {
        ctx
            .validateBody("name")
            .required("用户账号不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("pwd")
            .required("用户密码不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body; 
        // 查询账号是否存在
        let cardData = await userinfo.findOne(
            {
                where: {
                    username: reqBody.name
                }
            }
        );
        if (cardData) {
            ctx.body = util.resultError({ code: 0, message: '改账号已经存在了', data: null });
            return
        }
        //  生成加盐
        let salt = randomCoding();
        //  生成密码
        //  生成token 默认token
        let requestData = await userinfo.create({
            username: reqBody.name,
            pwdsalt: salt,
            userpwd: md5(reqBody.pwd + salt),
            token: randomCoding(16),
        })
        if (requestData) {
            ctx.body = util.resultSuccess({ message: '注册成功', data: null });
        } else {
            ctx.body = util.resultError({ code: 0, message: '注册失败，请稍后再试', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})


/**
 * 登录
 * */
router.post('/login', async (ctx) => {
    try {
        console.log('====',ctx.request.body);
        console.log('====',ctx.request.query);
        ctx
            .validateBody("name")
            .required("用户账号不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("pwd")
            .required("用户密码不能为空")
            .isString()
            .trim()
        
        

        let reqBody = ctx.request.body;
        // 查询账号是否存在
        let cardData = await userinfo.findOne(
            {
                where: {
                    username: reqBody.name
                }
            }
        );
        if (!cardData) {
            ctx.body = util.resultError({ code: 0, message: '登录失败，该账号不存在', data: null });
            return
        }
        // 加盐
        if (md5(reqBody.pwd + cardData.pwdsalt) == cardData.userpwd) {
            let payload = {
                "name": md5(cardData.username),
                "userid": md5(cardData.id)
            }
            let newToken = jwt.sign(payload, 'itliuyang', { expiresIn: 60000 });
            console.log(newToken);
            let updateInfo = await userinfo.update({
                token: newToken
            }, {
                where: {
                    id: cardData.id
                }
            })
            if (updateInfo) {
                ctx.body = util.resultSuccess({
                    message: '登录成功', data: {
                        token: newToken
                    }
                });
            } else {
                ctx.body = util.resultError({ code: 0, message: '登录失败，请稍后再试', data: null })
            }

        } else {
            ctx.body = util.resultError({ code: 0, message: '登录失败，账号或者密码错误', data: null });
        }
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
module.exports = router.routes(); 